package com.best4cloud.auth.security.wechat.unionid;

import com.best4cloud.auth.service.BestUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class UnionIdAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private BestUserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UnionIdAuthenticationToken authenticationToken = (UnionIdAuthenticationToken) authentication;
        String unionId = (String) authenticationToken.getPrincipal();
        UserDetails user = userDetailsService.loadUserByUnionId(unionId);
        if (user == null) {
            throw new InternalAuthenticationServiceException("账户名或密码错误！");
        }
        UnionIdAuthenticationToken authenticationResult = new UnionIdAuthenticationToken(unionId, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return UnionIdAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
